package one.chchy.plearning.ui.home;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContract;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import one.chchy.plearning.databinding.FragmentHomeBinding;

public class HomeFragment extends Fragment {

    private FragmentHomeBinding binding;

    private static final int REQUEST_CODE_GALLERY = 1;
    private static final int REQUEST_CODE_FILE = 2;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        HomeViewModel homeViewModel =
                new ViewModelProvider(this).get(HomeViewModel.class);

        binding = FragmentHomeBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        ActivityResultContract<String, Uri> getContentContract = new ActivityResultContracts.GetContent();
        ActivityResultLauncher<String> getContent = registerForActivityResult(getContentContract, new ActivityResultCallback<Uri>() {
            @Override
            public void onActivityResult(Uri uri) {
                // 在这里处理返回的Uri
                if (uri != null) {
                    binding.imageView.setImageURI(uri);
                }
            }
        });

        binding.imageView.setOnClickListener(v -> {
            new AlertDialog.Builder(getContext())
                    .setTitle("选择图片来源")
                    .setItems(new String[]{"图库", "文件夹"}, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (which == 0) {
                                // 打开图片浏览器
                                Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
                                intent.addCategory(Intent.CATEGORY_OPENABLE);
                                intent.setType("image/*");
                                getContent.launch(intent);
                            } else {
                                // 打开文件浏览器
                                getContent.launch("image/*");
                            }
                        }
                    })
                    .show();
        });

        return root;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}